<template>
  <el-dialog title="权限设置" :width="750" v-model="visible" @closed="$emit('closed')">
	  <el-form label-width="110px">
		  <el-form-item label="应用访问权限">
			  <el-select v-model="form.roleType" @change="changeType" placeholder="请选择..." style="width:100%">
				  <el-option
					  v-for="item in dataScopeOptions"
					  :key="item.value"
					  :label="item.label"
					  :value="item.value"
				  ></el-option>
			  </el-select>
		  </el-form-item>
	  </el-form>
	  <el-tabs type="card" tab-position="left" v-show="form.roleType=='2'">
		<el-tab-pane label="部门配置">
			<div class="treeMain" style="width: 100%;">
				<el-tree ref="dept" node-key="id" :data="data.list" :props="data.props" default-expand-all show-checkbox></el-tree>
			</div>
		</el-tab-pane>
		<el-tab-pane label="岗位配置">
			<div style="padding: 5px;">
				<el-checkbox-group v-model="form.postList">
					<el-checkbox v-for="item in postList" :label="item.id + ''" :key="item.id" style="width: 100px">{{item.fullName}}</el-checkbox>
				</el-checkbox-group>
			</div>
		</el-tab-pane>
		<el-tab-pane label="角色配置">
			<div style="padding: 5px;">
				<el-checkbox-group v-model="form.roleList">
					<el-checkbox v-for="item in roleList" :label="item.roleId+''" :key="item.roleId" style="width: 100px">{{item.roleName}}</el-checkbox>
				</el-checkbox-group>
			</div>
		</el-tab-pane>
		<el-tab-pane label="用户配置">
			<div class="user-select">
				<div class="user-select__left">
					<div class="user-select__search">
						<el-input v-model="keyword" prefix-icon="el-icon-search" placeholder="搜索成员">
							<template #append>
								<el-button icon="el-icon-search" @click="search"></el-button>
							</template>
						</el-input>
					</div>
					<div class="user-select__select">
						<div class="user-select__tree" v-loading="showGrouploading">
							<el-scrollbar>
								<el-tree class="menu" ref="groupTree" :data="group" :node-key="groupProps.key" :props="groupProps" highlight-current :expand-on-click-node="false" :default-expand-all="true" :current-node-key="groupId" @node-click="groupClick"/>
							</el-scrollbar>
						</div>
						<div class="user-select__user" v-loading="showUserloading">
							<div class="user-select__user__list">
								<el-scrollbar ref="userScrollbar">
									<el-tree class="menu" ref="userTree" :data="user" :node-key="userProps.key" :props="userProps" :default-checked-keys="selectedIds" show-checkbox check-on-click-node @check-change="userClick"></el-tree>
								</el-scrollbar>
							</div>
							<!--footer>
								<el-pagination background layout="prev,next" small :total="total" :page-size="pageSize" v-model:currentPage="currentPage" @current-change="paginationChange"></el-pagination>
							</footer-->
						</div>
					</div>
				</div>
				<div class="user-select__toicon"><el-icon><el-icon-arrow-right /></el-icon></div>
				<div class="user-select__selected">
					<header>已选 ({{selected.length}})</header>
					<ul>
						<el-scrollbar>
							<li v-for="(item, index) in selected" :key="item.id">
								<span class="name">
									<el-avatar size="small">{{item.name.substring(0,1)}}</el-avatar>
									<label>{{item.name}}</label>
								</span>
								<span class="delete">
									<el-button type="danger" icon="el-icon-delete" circle size="small" @click="deleteSelected(index)"></el-button>
								</span>
							</li>
						</el-scrollbar>
					</ul>
				</div>
			</div>
		</el-tab-pane>
	  </el-tabs>

	  <template #footer>
		  <el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		  <el-button @click="visible=false" >取 消</el-button>
	  </template>
  </el-dialog>
</template>

<script>
import { Search } from "@element-plus/icons-vue"
import config from "@/config/workflow";
export default {
  data() {
    return {
      Search,
      visible: false,
      activeName: "first",
      userPhone: "",
	  form:{
		  roleType:'1'
	  },
	  isSaveing:false,
	  // 访问权限范围
	  dataScopeOptions: [
	  	{
	  		value: "1",
	  		label: "所有人都可使用(公开应用的常规设置，该应用对所有人开放)"
	  	},
	  	{
	  		value: "2",
	  		label: "自定义访问权限(可按部门、岗位、角色配置用户的使用权限)"
	  	}
	  ],
	  showGrouploading: false,
	  showUserloading: false,
	  groupProps: config.group.props,
	  userProps: config.user.props,
	  group: [],
	  user: [],
	  pageSize: 10,
	  total: 0,
	  currentPage: 1,
	  groupId: '',
	  keyword: '',
	  searchForm:{},
	  selected: [],
	  postList:[],
      roleList:[],
	  selectPost:[],
	  data: {
	  	dataType :"1",
	  	list: [],
	  	checked: [],
	  	props: {},
	  	rule: ""
	  },
    }
  },
  computed: {
  	selectedIds(){
  		return this.selected.map(t => t.id)
  	}
  },
  created() {
	this.form.appId = this.$route.query.appId;
    this.getDept();
	this.getGroup();
	this.getUser();
	this.getPost();
	this.getRole();
  },
  methods: {
    open() {
      this.visible = true
	  this.$nextTick(()=>{
	  	 this.getPermisson();
	  })
    },
    handleClick(tab, event) {
      console.log(tab, event)
    },
	// 获取部门树结构
	async getDept(){
		var res = await this.$API.system.dept.tree.get();
		if (res.code == 200){
			  this.data.list = res.data
		}
	},
	//获取组织
	async getGroup(){
		this.showGrouploading = true;
		//var res = await config.group.apiObj.get();
		var res = await this.$API.system.dept.tree.get();
		this.showGrouploading = false;
		//var allNode = {[config.group.props.key]: '', [config.group.props.label]: '所有'}
		//res.data.unshift(allNode);
		this.group = config.group.parseData(res).rows
	},
	 //获取用户
	 async getUser(){
		this.showUserloading = true;
		let res = await this.$API.system.member.getMemberByDept.list.get(this.searchForm)
		if (res.code == 200){
			  this.user =  res.data.rows;
			  this.total = res.data.total;
			  //this.$refs.userScrollbar.setScrollTop(0)
		}
		this.showUserloading = false;
	 },
	  // 获取所有岗位
	  async getPost() {
		  let res = await this.$API.system.post.getAllPost.get({})
		  if (res.code == 200){
			 this.postList = res.data;
		  }
	  },
	  // 获取用户角色
	  async getRole() {
		  let res = await this.$API.system.role.list.get({pageSize: 100, roleType: 1})
		  if (res.code == 200){
			  this.roleList = res.data.rows;
		  }
	  },
	  //用户搜索
	  search(){
		  // 名称
		  this.searchForm.name = this.keyword;
		  // 当前页码
		  this.searchForm.pageNum = 1
		  // 页面大小
		  this.searchForm.pageSize = this.pageSize;
		  this.getUser(this.searchForm)
	  },
	  //删除已选
	  deleteSelected(index){
		  this.selected.splice(index,1);
		  this.$refs.userTree.setCheckedKeys(this.selectedIds)

	  },
	  //提交保存
	  save(){
		  this.value.splice(0,this.value.length);
		  this.selected.map(item => {
			  this.value.push(item)
		  })
		  this.dialogVisible = false
	  },
	  //组织点击
	  groupClick(data){
		  // 名称
		  this.searchForm.name = ''
		  // 当前页码
		  this.searchForm.pageNum = 1
		  // 页面大小
		  this.searchForm.pageSize = this.pageSize;
		  // 部门
		  this.searchForm.deptId = data[config.group.props.key]
		  this.getUser(this.searchForm)
	  },
	  //用户点击
	  userClick(data, checked){
		  if(checked){
			  this.selected.push({
				  id: data[config.user.props.key],
				  name: data[config.user.props.label],
			  })
		  }else{
			  this.selected = this.selected.filter(item => item.id != data[config.user.props.key])
		  }
	  },
	  //用户分页点击
	  paginationChange(){
		  this.searchForm.pageNum = this.currentPage;
		  this.getUser()
	  },
	  // 获取权限信息
	  async getPermisson() {
		  let res = await this.$API.app.appStore.getAppPermisson.get(this.form.appId);
		  if (res.code == 200){
			   if (res.data.roleType == '2'){
				   this.selected = res.data.userList
				   for (let i = 0; i < res.data.deptList.length; i++) {
					   if (res.data.deptList[i] == 100 && i !=0){
						   res.data.deptList.splice(i)
					   }
				   }
				   this.$nextTick(()=>{
					   this.$refs.dept.setCheckedKeys(res.data.deptList)
				   })
			   }
			  console.log(res.data)
			  Object.assign(this.form,res.data)
		  }
	  },
	  // 提交事件
	  async submit() {
		  if (this.form.roleType == '2'){
			  // 部门权限
			  var deptList = this.$refs.dept.getCheckedKeys().concat(this.$refs.dept.getHalfCheckedKeys())
			  this.form.deptList = deptList;
		  }
		  if (this.selected.length > 0){
			  let userId = []
			  this.selected.map((item) => {
				  userId.push(item.id)
			  })
			  this.form.userList = userId;
		  }
		  let res = await this.$API.app.appStore.savePermisson.post(this.form)
		  if (res.code == 200){
			  this.$message.success("保存成功");
		  }else {
			  this.$message.error("保存失败")
		  }
		  this.visible = false;
	  },
	  // 类型改变
	  changeType(env){
		  if (env == 2){
			  this.$nextTick(() =>{
				  console.log(this.$refs.dept)
			  })

		  }
	  }
  },
}
</script>

<style lang="scss" scoped>
.user-add-page {
  .user-add-page:deep(.el-aside .el-header) {
    padding: 0;
  }
}
 .treeMain {height:280px;overflow: auto;border: 1px solid #dcdfe6;margin-bottom: 10px;}
.user-select {display: flex;}
.user-select__left {width: 350px;}
.user-select__right {flex: 1;}

.user-select__search {padding-bottom:10px;}

.user-select__select {display: flex;border: 1px solid var(--el-border-color-light);background: var(--el-color-white);}
.user-select__tree {width: 200px;height:300px;border-right: 1px solid var(--el-border-color-light);}
.user-select__user {width: 200px;height:300px;display: flex;flex-direction: column;}
.user-select__user__list {flex: 1;overflow: auto;}
.user-select__user footer {height:36px;padding-top:5px;border-top: 1px solid var(--el-border-color-light);}

.user-select__toicon {display: flex;justify-content: center;align-items: center;margin:0 10px;}
.user-select__toicon i {display: flex;justify-content: center;align-items: center;background: #ccc;width: 20px;height: 20px;text-align: center;line-height: 20px;border-radius:50%;color: #fff;}

.user-select__selected {height:345px;width: 200px;border: 1px solid var(--el-border-color-light);background: var(--el-color-white);}
.user-select__selected header {height:43px;line-height: 43px;border-bottom: 1px solid var(--el-border-color-light);padding:0 15px;font-size: 12px;}
.user-select__selected ul {height:300px;overflow: auto;}
.user-select__selected li {display: flex;align-items: center;justify-content: space-between;padding:5px 5px 5px 15px;height:38px;}
.user-select__selected li .name {display: flex;align-items: center;}
.user-select__selected li .name .el-avatar {background: #409eff;margin-right: 10px;}
.user-select__selected li .name label {}
.user-select__selected li .delete {display: none;}
.user-select__selected li:hover {background: var(--el-color-primary-light-9);}
.user-select__selected li:hover .delete {display: inline-block;}

.user-select-role .user-select__left {width: 200px;}
.user-select-role .user-select__tree {border: none;height: 343px;}
.user-select-role .user-select__selected {}

[data-theme='dark'] .user-select__selected li:hover {background: rgba(0, 0, 0, 0.2);}
[data-theme='dark'] .user-select__toicon i {background: #383838;}
</style>
